// 简易 WebSocket 客户端，带心跳与自动重连
export class WSClient {
  constructor(url, { heartbeatInterval = 15000, reconnectDelay = 3000 } = {}) {
    this.url = url
    this.heartbeatInterval = heartbeatInterval
    this.reconnectDelay = reconnectDelay
    this.ws = null
    this.timer = null
    this.onMessage = () => {}
    this.onStatus = () => {}
  }

  connect() {
    this.ws = new WebSocket(this.url)
    this.onStatus('connecting')

    this.ws.onopen = () => {
      this.onStatus('connected')
      this.startHeartbeat()
    }
    this.ws.onclose = () => {
      this.onStatus('disconnected')
      this.stopHeartbeat()
      setTimeout(() => this.connect(), this.reconnectDelay)
    }
    this.ws.onerror = () => {
      this.onStatus('error')
    }
    this.ws.onmessage = (ev) => {
      if (ev.data === 'pong') return
      this.onMessage(ev.data)
    }
  }

  startHeartbeat() {
    this.stopHeartbeat()
    this.timer = setInterval(() => {
      try { this.ws?.send('ping') } catch (_) {}
    }, this.heartbeatInterval)
  }

  stopHeartbeat() {
    if (this.timer) clearInterval(this.timer)
    this.timer = null
  }

  send(obj) {
    try { this.ws?.send(typeof obj === 'string' ? obj : JSON.stringify(obj)) } catch (_) {}
  }
}


